package com.tronsis.distribution.fragment.point;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.lzy.imagepicker.ImagePicker;
import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.me.points.PointProcessingDetailActivity;
import com.tronsis.distribution.bean.WithDrawAskBean;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.util.GlideImageLoader;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.fragment.BaseFragment;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.SRFConfigUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.widget.ConfirmDialog;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 积分提现处理
 *
 * @author scofield@tronsis.com
 * @date 2019/3/13 15:58
 */
public class PointProcessingFragment extends BaseFragment {

    @BindView(R.id.rv_stock_audit)
    RecyclerView mRvAudit;
    @BindView(R.id.srl_point)
    SwipeRefreshLayout mSrl;

    private CommonAdapter<WithDrawAskBean> mAdapter;
    private List<WithDrawAskBean> mDataList = new ArrayList<>();
    private String mState;
    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private LoadMoreWrapper mLoadMoreWrapper;


    @Override
    protected View onCreateView() {
        EventBus.getDefault().register(this);
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_point_processing, null);
        ButterKnife.bind(this, view);
        mState = getArguments().getString("state");
        return view;


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if ((requestCode == 100||requestCode == 200) && resultCode == Activity.RESULT_OK) {
//            getAskWithDraws(mPage,mSize,mState,true);
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMessage message) {
        if ("刷新列表".equals(message.getParams())) {
            getAskWithDraws(mPage, mSize, mState, true);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initData() {
        initRv();
        getAskWithDraws(mPage, mSize, mState, true);

    }

    private void initRv() {
        ImagePicker.getInstance().setImageLoader(new GlideImageLoader());
        SRFConfigUtil.initSwipeRefreshLayout(mSrl);
        mSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getAskWithDraws(1, mSize, mState, true);
            }
        });
        mAdapter = new CommonAdapter<WithDrawAskBean>(getContext(), mDataList, R.layout.item_point_processing) {
            @Override
            protected void convert(ViewHolder holder, final WithDrawAskBean withDrawAskBean, int position) {
                String name = withDrawAskBean.getName() == null ? "-" : withDrawAskBean.getName();
                holder.setText(R.id.tv_name, name);
                holder.setText(R.id.tv_time, DateUtil.getDateTimeString(withDrawAskBean.getCreatedOn()));
                holder.setText(R.id.tv_points, getString(R.string.format_ask_points, String.valueOf(withDrawAskBean.getPoint())));
                holder.setText(R.id.tv_amount, getString(R.string.format_amount, withDrawAskBean.getPointPrice()));
                if (StringUtil.isEquals(mState, "REPORT")) {
                    holder.getView(R.id.ll_delete).setVisibility(View.VISIBLE);
                    holder.getView(R.id.line2).setVisibility(View.VISIBLE);

                    holder.setOnClickListener(R.id.btn_delete, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
                                @Override
                                public void onLeftButtonClick(View view) {

                                }

                                @Override
                                public void onRightButtonClick(View view) {
                                    deleteAskWithDraw(withDrawAskBean.getId());
                                }
                            }).showDialog("确认删除？", "取消", "确定");
                        }
                    });
                } else {
                    holder.getView(R.id.ll_delete).setVisibility(View.GONE);
                    holder.getView(R.id.line2).setVisibility(View.GONE);
                }
            }
        };

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(mContext, PointProcessingDetailActivity.class);
                intent.putExtra("withDrawAskBean", mDataList.get(position));
                startActivityForResult(intent, 100);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mLoadMoreWrapper = new LoadMoreWrapper(mAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mDataList.size() % 15 == 0 && mDataList.size() > 0 && mDataList.size() < mTotal) {
                    mPage = (mDataList.size() / 15) + 1;
                    getAskWithDraws(mPage, mSize, mState, false);
                }
            }
        });

        int height = DisplayUtil.getInstance(getContext()).dp2px(14);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(getContext(), MyDecoration.VERTICAL_LIST, height, color);
        mRvAudit.addItemDecoration(decoration);
        mRvAudit.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvAudit.setAdapter(mLoadMoreWrapper);
    }

    //get ask with draws
    private void getAskWithDraws(int page, int size, final String state, final boolean isRefresh) {

        try {
            UserBizFactory.createBiz().getPointAskWithDraw(getActivity(), page, size, state, new UICallBack() {
                @Override
                public void onStart() {
                    if (isRefresh) {
                        mSrl.setRefreshing(true);
                    }
//                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    mSrl.setRefreshing(false);
//                    dismissLoadingDialog();
                    ListBean listBean = (ListBean) data;
                    mTotal = listBean.getTotal();
                    List<WithDrawAskBean> list = listBean.getList();
                    if (isRefresh) {
                        mDataList.clear();
                        mDataList.addAll(list);
                    } else {
                        mDataList.addAll(list);
                    }
                    mLoadMoreWrapper.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int status) {
                    mSrl.setRefreshing(false);
//                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            mSrl.setRefreshing(false);
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void deleteAskWithDraw(String askWithDrawId) {
        try {
            UserBizFactory.createBiz().deletePointAskWithDraw(getActivity(), askWithDrawId, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    getAskWithDraws(mPage, mSize, mState, true);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }
}
